package com.cxs.videoplayer.util;

import com.cxs.videoplayer.data.VideoInfo;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class VideoUtils {

    private final static String resFile = "resources/rawfile/videos.json";
    private final static String DEFAULT_THUMBNAIL = "entry/resources/base/media/thumbnail_default.jpeg";
    private static final int NEWS_CONTENT_SIZE = 1024;
    private static final int EOF = -1;
    private static Context context;

    private VideoUtils(){}

    public static List<VideoInfo> getVideoInfo(Context context) {
        VideoUtils.context = context;
        String jsonFile = getJsonFile(resFile);

        ZSONObject zsonObject = ZSONObject.stringToZSON(jsonFile);
        int total = zsonObject.getIntValue("total");
        ZSONArray details = zsonObject.getZSONArray("detail");
        List<VideoInfo> videoInfos = new ArrayList<>();
        for (int i = 0; i < total; i++) {
            ZSONObject detail = details.getZSONObject(i);
            VideoInfo videoInfo = new VideoInfo(i,
                    detail.getString("url"),
                    detail.getString("title"),
                    detail.getString("thumbnail"),
                    detail.getString("synopsis"));
            videoInfos.add(videoInfo);
        }
        return videoInfos;
    }

    private static String getJsonFile(String f) {
        try {
            Resource resource = context.getResourceManager().getRawFileEntry(f).openRawFile();
            byte[] tmp = new byte[NEWS_CONTENT_SIZE * NEWS_CONTENT_SIZE];
            int reads = resource.read(tmp);
            if (reads != EOF) {
                return new String(tmp, 0, reads, StandardCharsets.UTF_8);
            }
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
        return "";
    }

    public static PixelMap getPixelMap(String resFile) {
        if (resFile == null || resFile.equals("")) {
            resFile = DEFAULT_THUMBNAIL;
        }
        try {
            InputStream inputStream = context.getResourceManager().getRawFileEntry(resFile).openRawFile();
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/jpg";
            ImageSource imageSource = ImageSource.create(inputStream, srcOpts);
            PixelMap pixelMap = imageSource.createPixelmap(null);
            return pixelMap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
